<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"  v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="Employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="100" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="120" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="100" sortable>
			</el-table-column>
            <el-table-column prop="salt" label="salt" width="150" sortable>
            </el-table-column>
            <el-table-column prop="password" label="password" width="150" sortable>
            </el-table-column>
			<el-table-column prop="age" label="年龄" min-width="100" sortable>
			</el-table-column>
            <el-table-column prop="state" label="状态" width="100" :formatter="formatState" sortable>
            </el-table-column>
            <el-table-column prop="department.name" label="所属部门" min-width="100" sortable>
            </el-table-column>

            <!-- 这里不展示角色， 新增展示一个角色字段  -->
<!--            <el-table-column prop="allRole"  label="角色" width="180">
                <template slot-scope="scope">
                    <div slot="reference" class="name-wrapper" v-for="(item,index) in scope.row.allRole" :key="index">
                        <el-tag>{{ item.name }}</el-tag>
                    </div>
                </template>
            </el-table-column>-->

            <el-table-column prop="logininfoId" label="logininfoId" min-width="100" sortable>
            </el-table-column>
            <el-table-column prop="shopId" label="shopId" min-width="100" sortable>
            </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger"  v-perm="'employee:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" :current-page="currentPage"  style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面（新增和修改页面）-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
                <!--   学了手机注册添加user表和logininfo表后添加了一个密码字段  -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="editForm.password" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="电话" prop="phone">
                    <el-input v-model="editForm.phone" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" >
                    <el-input v-model="editForm.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="年龄">
                    <el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
                </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
                <el-form-item label="所属部门" >
                    <!--  级联表，无限极树  -->
                    <el-cascader
                            v-model="editForm.departmentId"
                            :options="departmentsTreee"
                            :props="{
                                checkStrictly: true,
                                value:'id',
                                label:'name',
                            }"
                            clearable
                    ></el-cascader>
                </el-form-item>

                <!--  新增一个角色选项（多选） -->
                <el-form-item label="角色选择" prop="roleIds">
                    <el-select v-model="editForm.roleIds" multiple placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :label="item.name"
                                :value="item.id">
                            <span style="float: left">{{ item.name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
                roleList:[],
                departmentsTreee:[],
                title:'',
				filters: {
                    keyword: ''
				},
				Employees: [],
				total: 0,
                pageSize:5,
                currentPage:1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    password: [
                        { required: true, message: '请设置初始密码', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ]
				},
				//编辑界面数据
				editForm: {
					id: null,
					username: '',
					phone: '',
					email: '',
					age: 0,
					state: 0,
                    departmentId: null,
                    password:"", // 学了手机注册添加user表和logininfo表后添加一个密码字段

                    // 角色多选字段
                    roleIds:null,
				},
			}
		},
		methods: {
            // 向后端发送请求，获取所有角色
            getRoles(){
                this.$http.get("/role")
                    .then(result=>{
                        // 请求后端接口成功
                        this.roleList = result.data;
                    })
                    .catch(result=>{
                        // 请求后端接口失败
                    })
            },

            // 向后端发送请求，获取部门无限极树
            getDepartmentsTreee(){
                this.$http.get("/dept/tree")
                    .then(result=>{
                        // 请求后端接口成功
                        this.departmentsTreee = result.data;
                    })
                    .catch(result=>{
                        // 请求后端接口失败
                    })

            },
            //员工状态显示转换
            formatState: function (row, column) {
                return row.state == 1 ? '启用' : row.state == 0 ? '禁用' : '未知';
            },
            // 监听当前页数的变化
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},

            // 关键字查询的函数
            search(){
                this.currentPage=1;
                this.getEmployees();
            },

			//获取员工列表
			getEmployees() {
				let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword:this.filters.keyword,
					// name: this.filters.name
				};
				this.listLoading = true;
				// 向后端发送查询所有员工的请求
                this.$http.post('/emp/query',para)
                    .then(result=>{
                        // 请求后端接口成功
                        this.listLoading = false;
                        // 接收并处理后端返回的结果
                        this.Employees = result.data.rows;
                        this.total = result.data.totals;
                    })
                    .catch(result=>{
                        // 请求后端接口失败
                        this.editLoading = false;
                        //给出提示
                        this.$message({
                            message: '请求后端接口失败',
                            type: 'error'
                        });
                    })

                //NProgress.start();
				/*getUserListPage(para).then((res) => {
					this.total = res.data.total;
					this.Employees = res.data.Employees;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//单个删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// let para = { id: row.id };
                    // 向后端发送根据id删除的请求
                    this.$http.delete("/emp/del/" + row.id )
                        .then(result=>{
                            // 关闭忙等
                            this.listLoading = false;
                            // 请求接口成功， 接收后端返回的结果
                            result = result.data;
                            // 对结果进行判断
                            if(result.success){
                                // 删除成功，给出提示
                                this.$message({
                                    message: result.msg,
                                    type: 'success'
                                });
                                // 删除成功后重新查询
                                this.currentPage=1;
                                this.getEmployees();
                            }else{
                                // 删除失败
                                // 关闭忙等
                                this.listLoading = false;
                                // 给出删除失败的提示
                                this.$message({
                                    message: result.msg,
                                    type: 'error'
                                });
                                // 重新查询
                                this.currentPage=1;
                                this.getEmployees();
                            }
                        })
                        .catch(result=>{
                            // 关闭忙等
                            this.listLoading = false;
                            //请求后端接口失败，给出提示
                            this.$message({
                                message: '请求接口失败',
                                type: 'error'
                            });
                        })

				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                this.title = '编辑';
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
                this.title = '新增';
				this.editFormVisible = true; // 点击新增按钮就开启模态框
				this.editForm = {
                    id: null,
                    username: '',
                    phone: '',
                    email: '',
                    age: 0,
                    state: 0,
                    departmentId: null,
                    // 角色多选字段
                    roleIds:null,
				};
			},
			//编辑(向后端发送新增或者修改的请求)
			editSubmit: function () {
                // 校验参数
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = Object.assign({}, this.editForm);
                            // 手动取出级联表中id数组中的最后一条数据
                            // 取出id数组中的最后一条数据
                            if(para.departmentId && para.departmentId instanceof Array){
                                para.departmentId = para.departmentId[para.departmentId.length-1];
                            }
							// 向后端发送新增或者修改的请求
                            this.$http.put("/emp/addOrUpdate",para)
                                .then(result=>{
                                    // 关闭忙等
                                    this.editLoading = false;
                                    // 关闭模态框
                                    this.editFormVisible = false;
                                    // 请求接口成功， 接收后端返回的结果
                                    result = result.data;
                                    // 对结果进行判断
                                    if(result.success){
                                        // 新增或修改成功，给出提示
                                        this.$message({
                                            message: result.msg,
                                            type: 'success'
                                        });
                                        // 新增或修改成功后重新查询
                                        this.currentPage=1;
                                        this.getEmployees();
                                    }else{
                                        // 新增或修改失败
                                        // 关闭忙等
                                        this.listLoading = false;
                                        // 关闭模态框
                                        this.editFormVisible = false;
                                        // 给出新增或修改失败的提示
                                        this.$message({
                                            message: result.msg,
                                            type: 'error'
                                        });
                                        // 重新查询
                                        this.currentPage=1;
                                        this.getEmployees();
                                    }
                                })
                                .catch(result=>{
                                    // 关闭忙等
                                    this.listLoading = false;
                                    // 关闭模态框
                                    this.editFormVisible = false;
                                    //请求后端接口失败，给出提示
                                    this.$message({
                                        message: '请求接口失败',
                                        type: 'error'
                                    });
                                })
						});
					}
				});
			},
			selsChange: function (sels) {
				// 批量删除选中的所有行数据
                this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
                // 获取选中的所有行数据的中的id集合
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// 向后端发送批量删除的请求
                    this.$http.patch("/emp/batch",ids)
                        .then(result=>{
                            // 关闭忙等
                            this.listLoading = false;
                            // 请求接口成功， 接收后端返回的结果
                            result = result.data;
                            // 对结果进行判断
                            if(result.success){
                                // 批量删除成功，给出提示
                                this.$message({
                                    message: result.msg,
                                    type: 'success'
                                });
                                // 批量删除成功后重新查询
                                this.currentPage=1;
                                this.getEmployees();
                            }else{
                                // 批量删除失败
                                // 关闭忙等
                                this.listLoading = false;
                                // 给出批量删除失败的提示
                                this.$message({
                                    message: result.msg,
                                    type: 'error'
                                });
                                // 重新查询
                                this.currentPage=1;
                                this.getEmployees();
                            }
                        })
                        .catch(result=>{
                            // 关闭忙等
                            this.listLoading = false;
                            //请求后端接口失败，给出提示
                            this.$message({
                                message: '请求接口失败',
                                type: 'error'
                            });
                        })
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getEmployees();
            // 查询获取无限极树（级联表）
            this.getDepartmentsTreee();
            // 获取所有角色
            this.getRoles();
		}
	}

</script>

<style scoped>

</style>